package Registry;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RemoteServer;
import java.rmi.server.ServerNotActiveException;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;

import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;

import General.RegistryInterface;

public class MyRegistryService extends UnicastRemoteObject implements RegistryInterface {
	
	private static final long serialVersionUID = 1L;
	private Registry fLocalRegistry;
	private int fPort;
	private HashMap<String, String> fRegisteredServices;

	public MyRegistryService(int port) throws RemoteException {
		super(0, new SslRMIClientSocketFactory(), new SslRMIServerSocketFactory(null, null, true));
		fPort = port;
		fLocalRegistry = LocateRegistry.getRegistry(null, fPort);
		fRegisteredServices = new HashMap<String, String>();
	}
	
	public void rebind(String name, Remote object) throws RemoteException {
		// Access control to allow only the server which originally registered for the service
		String clientHost = "";
		try {
			clientHost = RemoteServer.getClientHost();
		} catch (ServerNotActiveException e) {
			e.printStackTrace();
		}
		if (fRegisteredServices.containsKey(name)) {
			if (!fRegisteredServices.get(name).equals(clientHost)) {
				throw new RemoteException("Registry rebind refused");
			}
		}
		
		// Bind service
		fLocalRegistry.rebind(name, object);
		fRegisteredServices.put(name, clientHost);
	}
}
